import { PageContainer } from '@ant-design/pro-components';
import { ProDescriptions } from '@ant-design/pro-components';
import { useModel, history } from '@umijs/max';
import { Card, theme, Modal, Input, message, Select } from 'antd';
import React, { useState, useEffect, useCallback } from 'react';

const { Option } = Select;

const Wallet: React.FC = () => {
  const { token } = theme.useToken();
  const { initialState } = useModel('@@initialState');
  const [isRechargeModalVisible, setIsRechargeModalVisible] = useState(false);
  const [isPasswordModalVisible, setIsPasswordModalVisible] = useState(false);
  const [isPhoneModalVisible, setIsPhoneModalVisible] = useState(false);
  const [rechargeAmount, setRechargeAmount] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [isPaymentMethodModalVisible, setIsPaymentMethodModalVisible] = useState(false);
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState('');
  const [walletInfo, setWalletInfo] = useState({
    balance: 1000.5,
    lastRecharge: '2023-06-24',
    lastTransaction: '2023-06-23',
    lastTransactionAmount: -50.25,
    activeProducts: 2,
    paymentMethod: 'creditCard',
    availableCoupons: 3,
    autoRenew: true,
  });

  const updateWalletInfo = useCallback((updates) => {
    setWalletInfo((prevInfo) => ({ ...prevInfo, ...updates }));
  }, []);

  const fetchWalletInfo = useCallback(async () => {
    // 这里应该是一个真实的API调用
    // 现在我们只是返回当前的walletInfo状态
    return Promise.resolve({
      success: true,
      data: walletInfo,
    });
  }, [walletInfo]);

  const showRechargeModal = (amount = '') => {
    setRechargeAmount(amount);
    setIsRechargeModalVisible(true);
  };

  const showPasswordModal = () => {
    setIsPasswordModalVisible(true);
  };

  const showPhoneModal = () => {
    setIsPhoneModalVisible(true);
  };

  const handleRechargeOk = () => {
    const newBalance = parseFloat(walletInfo.balance) + parseFloat(rechargeAmount);
    updateWalletInfo({
      balance: newBalance,
      lastRecharge: new Date().toISOString().split('T')[0],
    });
    setIsRechargeModalVisible(false);
    message.success(`充值成功！金额: ¥${rechargeAmount}`);
    setRechargeAmount('');
  };

  const handlePasswordOk = () => {
    console.log('新支付密码:', newPassword);
    setIsPasswordModalVisible(false);
    message.success('支付密码修改成功！');
    setNewPassword('');
  };

  const handlePhoneOk = () => {
    console.log('新手机号:', phoneNumber);
    setIsPhoneModalVisible(false);
    message.success(`手机号绑定成功！新手机号: ${phoneNumber}`);
    setPhoneNumber('');
  };

  const handleCancel = (modalType) => {
    switch (modalType) {
      case 'recharge':
        setIsRechargeModalVisible(false);
        setRechargeAmount('');
        break;
      case 'password':
        setIsPasswordModalVisible(false);
        setNewPassword('');
        break;
      case 'phone':
        setIsPhoneModalVisible(false);
        setPhoneNumber('');
        break;
      case 'paymentMethod':
        setIsPaymentMethodModalVisible(false);
        setSelectedPaymentMethod('');
        break;
    }
  };

  const goToTransactionRecord = () => {
    history.push('/user/purchaseRecords');
  };

  const showPaymentMethodModal = () => {
    setIsPaymentMethodModalVisible(true);
  };

  const handlePaymentMethodOk = () => {
    updateWalletInfo({ paymentMethod: selectedPaymentMethod });
    setIsPaymentMethodModalVisible(false);
    message.success(`支付方式已更新为: ${selectedPaymentMethod}`);
    setSelectedPaymentMethod('');
  };

  return (
    <PageContainer>
      <Card
        style={{
          borderRadius: 8,
        }}
        bodyStyle={{
          backgroundImage:
            initialState?.settings?.navTheme === 'realDark'
              ? 'background-image: linear-gradient(75deg, #1A1B1F 0%, #191C1F 100%)'
              : 'background-image: linear-gradient(75deg, #FBFDFF 0%, #F5F7FF 100%)',
        }}
      >
        <div
          style={{
            backgroundPosition: '100% -30%',
            backgroundRepeat: 'no-repeat',
            backgroundSize: '274px auto',
            backgroundImage:
              "url('https://gw.alipayobjects.com/mdn/rms_a9745b/afts/img/A*BuFmQqsB2iAAAAAAAAAAAAAAARQnAQ')",
          }}
        >
          <ProDescriptions
            title="钱包信息"
            dataSource={walletInfo}
            columns={[
              {
                title: '账户余额',
                key: 'balance',
                dataIndex: 'balance',
                valueType: 'money',
                fieldProps: {
                  prefix: '¥',
                },
              },
              {
                title: '上次充值',
                key: 'lastRecharge',
                dataIndex: 'lastRecharge',
                valueType: 'date',
              },
              {
                title: '最近交易',
                key: 'lastTransaction',
                dataIndex: 'lastTransaction',
                valueType: 'date',
              },
              {
                title: '最近交易金额',
                key: 'lastTransactionAmount',
                dataIndex: 'lastTransactionAmount',
                valueType: 'money',
                fieldProps: {
                  prefix: '¥',
                },
              },
              {
                title: '激活产品数',
                key: 'activeProducts',
                dataIndex: 'activeProducts',
              },
              {
                title: '支付方式',
                key: 'paymentMethod',
                dataIndex: 'paymentMethod',
                valueType: 'select',
                valueEnum: {
                  creditCard: { text: '信用卡' },
                  debitCard: { text: '借记卡' },
                  alipay: { text: '支付宝' },
                  wechatPay: { text: '微信支付' },
                },
                render: (_, record) => (
                  <>
                    {record.paymentMethod} <a onClick={showPaymentMethodModal}>修改</a>
                  </>
                ),
              },
              {
                title: '可用优惠券',
                key: 'availableCoupons',
                dataIndex: 'availableCoupons',
              },
              {
                title: '自动续费',
                key: 'autoRenew',
                dataIndex: 'autoRenew',
                valueType: 'switch',
              },
              {
                title: '操作',
                valueType: 'option',
                render: () => [
                  <a key="recharge" onClick={() => showRechargeModal()}>充值</a>,
                  <a key="transactions" onClick={goToTransactionRecord}>交易记录</a>,
                ],
              },
            ]}
          >
            <ProDescriptions.Item label="快速充值">
              <a onClick={() => showRechargeModal('100')}>充值 ¥100</a> |
              <a onClick={() => showRechargeModal('500')}>充值 ¥500</a> |
              <a onClick={() => showRechargeModal()}>自定义金额</a>
            </ProDescriptions.Item>
            <ProDescriptions.Item label="账户安全">
              <a onClick={showPasswordModal}>修改支付密码</a> | <a onClick={showPhoneModal}>绑定手机号</a>
            </ProDescriptions.Item>
          </ProDescriptions>
        </div>
      </Card>

      <Modal
        title="充值"
        visible={isRechargeModalVisible}
        onOk={handleRechargeOk}
        onCancel={() => handleCancel('recharge')}
      >
        <Input
          placeholder="请输入充值金额"
          value={rechargeAmount}
          onChange={(e) => setRechargeAmount(e.target.value)}
          prefix="¥"
          type="number"
        />
      </Modal>

      <Modal
        title="修改支付密码"
        visible={isPasswordModalVisible}
        onOk={handlePasswordOk}
        onCancel={() => handleCancel('password')}
      >
        <Input.Password
          placeholder="请输入新的支付密码"
          value={newPassword}
          onChange={(e) => setNewPassword(e.target.value)}
        />
      </Modal>

      <Modal
        title="绑定手机号"
        visible={isPhoneModalVisible}
        onOk={handlePhoneOk}
        onCancel={() => handleCancel('phone')}
      >
        <Input
          placeholder="请输入新的手机号"
          value={phoneNumber}
          onChange={(e) => setPhoneNumber(e.target.value)}
        />
      </Modal>

      <Modal
        title="修改支付方式"
        visible={isPaymentMethodModalVisible}
        onOk={handlePaymentMethodOk}
        onCancel={() => handleCancel('paymentMethod')}
      >
        <Select
          style={{ width: '100%' }}
          placeholder="请选择支付方式"
          value={selectedPaymentMethod}
          onChange={(value) => setSelectedPaymentMethod(value)}
        >
          <Option value="creditCard">信用卡</Option>
          <Option value="debitCard">借记卡</Option>
          <Option value="alipay">支付宝</Option>
          <Option value="wechatPay">微信支付</Option>
        </Select>
      </Modal>
    </PageContainer>
  );
};

export default Wallet;